package JUC.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * JUC 版本
 * 线程之间的通信问题  等待通知，通知唤醒
 * 线程交替执行，A,B操作同一变量 num = 0
 * A num+1
 * B num-1
 * 判断时不能用if!!!会造成虚假唤醒
 */
public class B {
    public static void main(String[] args) {
        Date date = new Date();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    date.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    date.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();

    }
}

    //判断等待，业务，通知
  class Date2 { //数字   资源类
        private int number = 0;
        Lock lock=new ReentrantLock();
        //替代同步监视器
        Condition condition = lock.newCondition();

        //+1 如果当前数字不等于0，可以进行加一操作
        public  void increment() throws InterruptedException {

            while (number != 0) {
                //等待
              condition.await();
            }
            //0->1
            number++;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通知其他线程+1完毕
          condition.signalAll();
        }

        //-1
        public  void decrement() throws InterruptedException {
            while (number == 0) {
                //等待
               condition.await();
            }
            //1->0
            number--;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通知其他线程-1完毕
            condition.signalAll();
        }

    }

